{% extends 'base.html' %}
{% load static %}

{% block title %}{{ code.title }} - 文件管理{% endblock %}

{% block extra_css %}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-dark.min.css">
<style>
/* 游戏化深色主题样式 */
.container-fluid {
    color: rgba(255, 255, 255, 0.9) !important;
}

.file-tree {
    font-family: 'Courier New', monospace;
    background: linear-gradient(135deg, rgba(45, 55, 85, 0.3) 0%, rgba(35, 45, 75, 0.4) 100%) !important;
    border: 2px solid rgba(100, 150, 255, 0.5) !important;
    border-radius: 15px !important;
    padding: 1rem;
    max-height: 400px;
    overflow-y: auto;
    backdrop-filter: blur(15px);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3), 0 0 20px rgba(100, 150, 255, 0.2);
}

.file-tree-item {
    padding: 0.5rem;
    cursor: pointer;
    border-radius: 10px;
    transition: all 0.3s ease;
    color: rgba(255, 255, 255, 0.8) !important;
    margin-bottom: 0.25rem;
}

.file-tree-item:hover {
    background: rgba(100, 150, 255, 0.3) !important;
    color: white !important;
    transform: translateX(5px);
    box-shadow: 0 4px 15px rgba(100, 150, 255, 0.3);
}

.file-tree-item.selected {
    background: linear-gradient(135deg, rgba(100, 150, 255, 0.8), rgba(0, 212, 255, 0.8)) !important;
    color: white !important;
    border: 1px solid rgba(255, 255, 255, 0.3);
    box-shadow: 0 4px 15px rgba(100, 150, 255, 0.4);
}

.file-icon {
    width: 16px;
    height: 16px;
    margin-right: 0.5rem;
}

.folder-icon {
    color: #ffd700 !important;
}

.file-icon-text {
    color: rgba(100, 150, 255, 0.8) !important;
}

.main-file-badge {
    background: linear-gradient(135deg, rgba(0, 212, 255, 0.8), rgba(100, 150, 255, 0.8)) !important;
    color: white !important;
    font-size: 0.75rem;
    padding: 0.125rem 0.375rem;
    border-radius: 15px;
    margin-left: 0.5rem;
    border: 1px solid rgba(255, 255, 255, 0.3);
}

.file-content {
    background: linear-gradient(135deg, rgba(45, 55, 85, 0.3) 0%, rgba(35, 45, 75, 0.4) 100%) !important;
    border: 2px solid rgba(100, 150, 255, 0.5) !important;
    border-radius: 15px !important;
    padding: 1rem;
    max-height: 500px;
    overflow-y: auto;
    backdrop-filter: blur(15px);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3), 0 0 20px rgba(100, 150, 255, 0.2);
}

.file-stats {
    background: linear-gradient(135deg, rgba(45, 55, 85, 0.3) 0%, rgba(35, 45, 75, 0.4) 100%) !important;
    padding: 1rem;
    border-radius: 15px !important;
    margin-bottom: 1rem;
    border: 2px solid rgba(100, 150, 255, 0.5);
    backdrop-filter: blur(15px);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3), 0 0 20px rgba(100, 150, 255, 0.2);
    color: rgba(255, 255, 255, 0.9) !important;
}

.btn-group-custom {
    gap: 0.5rem;
}

/* 卡片样式 */
.card {
    background: linear-gradient(135deg, rgba(45, 55, 85, 0.3) 0%, rgba(35, 45, 75, 0.4) 100%) !important;
    border: 2px solid rgba(100, 150, 255, 0.5) !important;
    border-radius: 15px !important;
    backdrop-filter: blur(15px);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3), 0 0 20px rgba(100, 150, 255, 0.2);
}

.card-header {
    background: linear-gradient(135deg, rgba(100, 150, 255, 0.8), rgba(0, 212, 255, 0.8)) !important;
    border-bottom: 1px solid rgba(255, 255, 255, 0.2) !important;
    color: white !important;
    border-radius: 13px 13px 0 0 !important;
}

.card-body {
    color: rgba(255, 255, 255, 0.9) !important;
}

/* 按钮样式 */
.btn {
    border-radius: 10px !important;
    font-weight: 600;
    transition: all 0.3s ease;
}

.btn-primary {
    background: linear-gradient(135deg, rgba(100, 150, 255, 0.8), rgba(0, 212, 255, 0.8)) !important;
    border: 2px solid rgba(255, 255, 255, 0.3) !important;
    color: white !important;
}

.btn-primary:hover {
    background: linear-gradient(135deg, rgba(100, 150, 255, 1), rgba(0, 212, 255, 1)) !important;
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(100, 150, 255, 0.4);
}

.btn-success {
    background: linear-gradient(135deg, rgba(40, 167, 69, 0.8), rgba(0, 212, 255, 0.8)) !important;
    border: 2px solid rgba(255, 255, 255, 0.3) !important;
    color: white !important;
}

.btn-success:hover {
    background: linear-gradient(135deg, rgba(40, 167, 69, 1), rgba(0, 212, 255, 1)) !important;
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(40, 167, 69, 0.4);
}

.btn-info {
    background: linear-gradient(135deg, rgba(23, 162, 184, 0.8), rgba(0, 212, 255, 0.8)) !important;
    border: 2px solid rgba(255, 255, 255, 0.3) !important;
    color: white !important;
}

.btn-info:hover {
    background: linear-gradient(135deg, rgba(23, 162, 184, 1), rgba(0, 212, 255, 1)) !important;
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(23, 162, 184, 0.4);
}

.btn-secondary {
    background: linear-gradient(135deg, rgba(108, 117, 125, 0.8), rgba(60, 60, 80, 0.8)) !important;
    border: 2px solid rgba(255, 255, 255, 0.3) !important;
    color: white !important;
}

.btn-secondary:hover {
    background: linear-gradient(135deg, rgba(108, 117, 125, 1), rgba(60, 60, 80, 1)) !important;
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(108, 117, 125, 0.4);
}

/* 文件操作按钮样式 - 实心背景白色字体 */
.btn-outline-primary {
    background: linear-gradient(135deg, rgba(100, 150, 255, 0.9), rgba(0, 212, 255, 0.9)) !important;
    border: 2px solid rgba(255, 255, 255, 0.3) !important;
    color: white !important;
    font-weight: 600;
    box-shadow: 0 4px 15px rgba(100, 150, 255, 0.3);
}

.btn-outline-success {
    background: linear-gradient(135deg, rgba(40, 167, 69, 0.9), rgba(0, 212, 255, 0.9)) !important;
    border: 2px solid rgba(255, 255, 255, 0.3) !important;
    color: white !important;
    font-weight: 600;
    box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3);
}

.btn-outline-info {
    background: linear-gradient(135deg, rgba(23, 162, 184, 0.9), rgba(0, 212, 255, 0.9)) !important;
    border: 2px solid rgba(255, 255, 255, 0.3) !important;
    color: white !important;
    font-weight: 600;
    box-shadow: 0 4px 15px rgba(23, 162, 184, 0.3);
}

.btn-outline-danger {
    background: linear-gradient(135deg, rgba(220, 53, 69, 0.9), rgba(255, 100, 100, 0.9)) !important;
    border: 2px solid rgba(255, 255, 255, 0.3) !important;
    color: white !important;
    font-weight: 600;
    box-shadow: 0 4px 15px rgba(220, 53, 69, 0.3);
}

.btn-outline-primary:hover {
    background: linear-gradient(135deg, rgba(100, 150, 255, 1), rgba(0, 212, 255, 1)) !important;
    border-color: rgba(255, 255, 255, 0.5) !important;
    color: white !important;
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(100, 150, 255, 0.5);
}

.btn-outline-success:hover {
    background: linear-gradient(135deg, rgba(40, 167, 69, 1), rgba(0, 212, 255, 1)) !important;
    border-color: rgba(255, 255, 255, 0.5) !important;
    color: white !important;
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(40, 167, 69, 0.5);
}

.btn-outline-info:hover {
    background: linear-gradient(135deg, rgba(23, 162, 184, 1), rgba(0, 212, 255, 1)) !important;
    border-color: rgba(255, 255, 255, 0.5) !important;
    color: white !important;
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(23, 162, 184, 0.5);
}

.btn-outline-danger:hover {
    background: linear-gradient(135deg, rgba(220, 53, 69, 1), rgba(255, 100, 100, 1)) !important;
    border-color: rgba(255, 255, 255, 0.5) !important;
    color: white !important;
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(220, 53, 69, 0.5);
}

/* 文本样式 */
h2, h5 {
    color: rgba(255, 255, 255, 0.9) !important;
}

.text-muted {
    color: rgba(255, 255, 255, 0.5) !important;
}

/* 代码高亮容器 */
pre {
    background: rgba(0, 0, 0, 0.8) !important;
    border: 1px solid rgba(100, 150, 255, 0.3) !important;
    border-radius: 10px !important;
    color: rgba(255, 255, 255, 0.9) !important;
}

/* 警告框样式 */
.alert {
    border-radius: 10px !important;
    border: 1px solid rgba(100, 150, 255, 0.5) !important;
    backdrop-filter: blur(10px);
}

.alert-danger {
    background: linear-gradient(135deg, rgba(220, 53, 69, 0.2), rgba(139, 0, 0, 0.2)) !important;
    color: rgba(255, 255, 255, 0.9) !important;
}
</style>
{% endblock %}

{% block content %}
<div class="container-fluid mt-4">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <div class="flex-grow-1">
                    <div class="d-flex align-items-center">
                        <h2 class="mb-0 me-3" id="projectTitle">{{ code.title }}</h2>
                        {% if code_operations_enabled %}
                        <button class="btn btn-sm btn-outline-primary" onclick="openEditProjectModal()" title="编辑项目信息">
                            <i class="fas fa-edit"></i> 编辑
                        </button>
                        {% else %}
                        <div class="btn btn-sm btn-outline-primary disabled" onclick="showCodeOperationsDisabledAlert()" style="opacity: 0.5; cursor: pointer;" title="点击查看详情">
                            <i class="fas fa-edit"></i> 编辑
                        </div>
                        {% endif %}
                    </div>
                    <p class="text-muted mb-0 mt-2" id="projectDescription">{{ code.description|default:"无描述" }}</p>
                </div>
                <div class="btn-group-custom d-flex">
                    {% if code_operations_enabled %}
                    <a href="{% url 'codes:upload_files' code.id %}" class="btn btn-primary">
                        <i class="fas fa-upload"></i> 上传文件
                    </a>
                    <a href="{% url 'codes:create_file' code.id %}" class="btn btn-success">
                        <i class="fas fa-plus"></i> 新建文件
                    </a>
                    {% else %}
                    <div class="btn btn-primary disabled" onclick="showCodeOperationsDisabledAlert()" style="opacity: 0.5; cursor: pointer;" title="点击查看详情">
                        <i class="fas fa-upload"></i> 上传文件
                    </div>
                    <div class="btn btn-success disabled" onclick="showCodeOperationsDisabledAlert()" style="opacity: 0.5; cursor: pointer;" title="点击查看详情">
                        <i class="fas fa-plus"></i> 新建文件
                    </div>
                    {% endif %}
                    {% if files %}
                    <a href="{% url 'codes:download_project' code.id %}" class="btn btn-info">
                        <i class="fas fa-download"></i> 下载项目
                    </a>
                    {% endif %}
                    <a href="{% url 'codes:code_list' %}" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> 返回列表
                    </a>
                </div>
            </div>

            <!-- 项目统计信息 -->
            <div class="file-stats">
                <div class="row">
                    <div class="col-md-3">
                        <strong>文件数量:</strong> {{ code.get_file_count }}
                    </div>
                    <div class="col-md-3">
                        <strong>总大小:</strong> {{ total_size|filesizeformat }}
                    </div>
                    <div class="col-md-3">
                        <strong>编程语言:</strong> {{ code.get_language_display }}
                    </div>
                    <div class="col-md-3">
                        <strong>主文件:</strong>
                        {% if main_file %}
                            {{ main_file.file_path }}
                        {% else %}
                            <span class="text-muted">未设置</span>
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>
    </div>

    {% if files %}
    <div class="row">
        <!-- 文件 树 -->
        <div class="col-md-4">
            <div class="card">
                <div class="card-header">
                    <div class="d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">文件结构</h5>
                        <div>
                            {% if code_operations_enabled %}
                            <a href="{% url 'codes:upload_files' code.id %}" class="btn btn-outline-primary btn-sm">
                                <i class="fas fa-upload"></i> 上传文件
                            </a>
                            <a href="{% url 'codes:create_file' code.id %}" class="btn btn-outline-success btn-sm">
                                 <i class="fas fa-plus"></i> 新建文件
                             </a>
                            {% else %}
                            <div class="btn btn-outline-primary btn-sm disabled" onclick="showCodeOperationsDisabledAlert()" style="opacity: 0.5; cursor: pointer;" title="点击查看详情">
                                <i class="fas fa-upload"></i> 上传文件
                            </div>
                            <div class="btn btn-outline-success btn-sm disabled" onclick="showCodeOperationsDisabledAlert()" style="opacity: 0.5; cursor: pointer;" title="点击查看详情">
                                 <i class="fas fa-plus"></i> 新建文件
                             </div>
                            {% endif %}
                            <a href="{% url 'codes:download_project' code.id %}" class="btn btn-outline-info btn-sm">
                                <i class="fas fa-download"></i> 下载项目
                            </a>
                        </div>
                    </div>
                </div>
                <div class="card-body p-0">
                    <div class="file-tree" id="fileTree">
                        {% if code.get_file_count > 0 %}
                            {% for file in files %}
                            <div class="file-tree-item" data-file-id="{{ file.id }}" data-file-path="{{ file.file_path }}">
                                <i class="fas fa-file file-icon file-icon-text"></i>
                                {{ file.file_path }}
                                {% if file.is_main %}
                                    <span class="main-file-badge">主文件</span>
                                {% endif %}
                                <div class="float-end">
                                    <small class="text-muted">{{ file.file_size|filesizeformat }}</small>
                                    {% if code_operations_enabled %}
                                    <a href="{% url 'codes:edit_file' code.id file.id %}" class="btn btn-sm btn-outline-primary ms-1">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <a href="{% url 'codes:delete_file' code.id file.id %}" class="btn btn-sm btn-outline-danger ms-1">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                    {% else %}
                                    <div class="btn btn-sm btn-outline-primary ms-1 disabled" onclick="showCodeOperationsDisabledAlert()" style="opacity: 0.5; cursor: pointer;" title="点击查看详情">
                                        <i class="fas fa-edit"></i>
                                    </div>
                                    <div class="btn btn-sm btn-outline-danger ms-1 disabled" onclick="showCodeOperationsDisabledAlert()" style="opacity: 0.5; cursor: pointer;" title="点击查看详情">
                                        <i class="fas fa-trash"></i>
                                    </div>
                                    {% endif %}
                                </div>
                            </div>
                            {% endfor %}
                        {% else %}
                            <div class="text-center py-4 text-muted">
                                <i class="fas fa-folder-open fa-3x mb-3"></i>
                                <p>项目中还没有文件</p>
                                <p class="small">点击上方按钮开始添加文件</p>
                            </div>
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>

        <!-- 文件内容显示 -->
        <div class="col-md-8">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0" id="currentFileName">选择文件查看内容</h5>
                    <div id="fileActions" style="display: none;">
                        <button class="btn btn-sm btn-outline-secondary" onclick="copyContent()">
                            <i class="fas fa-copy"></i> 复制
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <div id="fileContentContainer">
                        <div class="text-center text-muted py-5">
                            <i class="fas fa-file-alt fa-3x mb-3"></i>
                            <p>点击左侧文件查看内容</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    {% else %}
    <div class="row">
        <div class="col-12">
            <div class="text-center py-5">
                <i class="fas fa-folder-open fa-4x text-muted mb-4"></i>
                <h4 class="text-muted">项目中还没有文件</h4>
                <p class="text-muted mb-4">开始上传文件或创建新文件来构建您的项目</p>
                <div class="btn-group-custom d-flex justify-content-center">
                    {% if code_operations_enabled %}
                    <a href="{% url 'codes:upload_files' code.id %}" class="btn btn-primary btn-lg">
                        <i class="fas fa-upload"></i> 上传文件
                    </a>
                    <a href="{% url 'codes:create_file' code.id %}" class="btn btn-success btn-lg">
                        <i class="fas fa-plus"></i> 新建文件
                    </a>
                    {% else %}
                    <div class="btn btn-primary btn-lg disabled" onclick="showCodeOperationsDisabledAlert()" style="opacity: 0.5; cursor: pointer;" title="点击查看详情">
                        <i class="fas fa-upload"></i> 上传文件
                    </div>
                    <div class="btn btn-success btn-lg disabled" onclick="showCodeOperationsDisabledAlert()" style="opacity: 0.5; cursor: pointer;" title="点击查看详情">
                        <i class="fas fa-plus"></i> 新建文件
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
    {% endif %}
</div>

<!-- 编辑项目信息模态框 -->
<div class="modal fade" id="editProjectModal" tabindex="-1" aria-labelledby="editProjectModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content" style="background: linear-gradient(135deg, rgba(45, 55, 85, 0.95) 0%, rgba(35, 45, 75, 0.95) 100%); border: 2px solid rgba(100, 150, 255, 0.5); border-radius: 15px; backdrop-filter: blur(15px);">
            <div class="modal-header" style="background: linear-gradient(135deg, rgba(100, 150, 255, 0.8), rgba(0, 212, 255, 0.8)); border-bottom: 1px solid rgba(255, 255, 255, 0.2); border-radius: 13px 13px 0 0;">
                <h5 class="modal-title" id="editProjectModalLabel" style="color: white;">编辑项目信息</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" style="color: rgba(255, 255, 255, 0.9);">
                <form id="editProjectForm">
                    {% csrf_token %}
                    <div class="mb-3">
                        <label for="titleInput" class="form-label">项目标题</label>
                        <input type="text" class="form-control" id="titleInput" 
                               style="background: rgba(255, 255, 255, 0.1); border: 1px solid rgba(100, 150, 255, 0.5); color: rgba(255, 255, 255, 0.9); border-radius: 8px;"
                               placeholder="请输入项目标题..." value="{{ code.title }}">
                    </div>
                    <div class="mb-3">
                        <label for="descriptionTextarea" class="form-label">项目描述</label>
                        <textarea class="form-control" id="descriptionTextarea" rows="4" 
                                  style="background: rgba(255, 255, 255, 0.1); border: 1px solid rgba(100, 150, 255, 0.5); color: rgba(255, 255, 255, 0.9); border-radius: 8px;"
                                  placeholder="请输入项目描述...">{{ code.description|default:"" }}</textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer" style="border-top: 1px solid rgba(255, 255, 255, 0.2);">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveProjectInfo()">保存</button>
            </div>
        </div>
    </div>
</div>

{% endblock %}

{% block extra_js %}
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-core.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/autoloader/prism-autoloader.min.js"></script>
<script>
// 显示代码操作功能禁用提示
function showCodeOperationsDisabledAlert() {
    alert('代码操作功能暂时不可用\n\n管理员已暂时关闭代码操作功能，包括上传文件、新建文件、编辑文件等操作。\n\n如有疑问，请联系管理员。');
}

// 文件选择和内容显示
document.addEventListener('DOMContentLoaded', function() {
    const fileTreeItems = document.querySelectorAll('.file-tree-item');
    const fileContentContainer = document.getElementById('fileContentContainer');
    const currentFileName = document.getElementById('currentFileName');
    const fileActions = document.getElementById('fileActions');
    let currentFileContent = '';

    fileTreeItems.forEach(item => {
        item.addEventListener('click', function() {
            // 移除其他选中状态
            fileTreeItems.forEach(i => i.classList.remove('selected'));
            // 添加选中状态
            this.classList.add('selected');

            const fileId = this.dataset.fileId;
            const filePath = this.dataset.filePath;

            // 加载文件内容
            loadFileContent(fileId, filePath);
        });
    });

    function loadFileContent(fileId, filePath) {
        fetch(`/codes/{{ code.id }}/api/file/${fileId}/`, {
            method: 'POST',
            headers: {
                'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
                'Content-Type': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                currentFileName.textContent = filePath;
                currentFileContent = data.content;

                // 获取文件扩展名来确定语言
                const extension = filePath.split('.').pop().toLowerCase();
                const language = getLanguageFromExtension(extension);

                // 显示代码内容
                fileContentContainer.innerHTML = `
                    <pre><code class="language-${language}">${escapeHtml(data.content)}</code></pre>
                `;

                // 应用语法高亮
                Prism.highlightAll();

                // 显示文件操作按钮
                fileActions.style.display = 'block';
            } else {
                fileContentContainer.innerHTML = `
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle"></i> 加载文件失败: ${data.error}
                                    </div>
                `;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            fileContentContainer.innerHTML = `
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle"></i> 网络错误，请重试
                </div>
            `;
        });
    }

    function getLanguageFromExtension(ext) {
        const languageMap = {
            'py': 'python',
            'js': 'javascript',
            'java': 'java',
            'cpp': 'cpp',
            'c': 'c',
            'h': 'c',
            'hpp': 'cpp',
            'html': 'html',
            'css': 'css',
            'json': 'json',
            'xml': 'xml',
            'yaml': 'yaml',
            'yml': 'yaml',
            'md': 'markdown',
            'txt': 'text'
        };
        return languageMap[ext] || 'text';
    }

    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // 复制内容功能
    window.copyContent = function() {
        if (currentFileContent) {
            navigator.clipboard.writeText(currentFileContent).then(() => {
                // 显示复制成功提示
                const btn = event.target.closest('button');
                const originalText = btn.innerHTML;
                btn.innerHTML = '<i class="fas fa-check"></i> 已复制';
                btn.classList.add('btn-success');
                btn.classList.remove('btn-outline-secondary');

                setTimeout(() => {
                    btn.innerHTML = originalText;
                    btn.classList.remove('btn-success');
                    btn.classList.add('btn-outline-secondary');
                }, 2000);
            }).catch(err => {
                console.error('复制失败:', err);
                alert('复制失败，请手动复制');
            });
        }
    };

    // 文件操作函数
    window.editFile = function(event, fileId) {
        event.stopPropagation();
        window.location.href = `/codes/{{ code.id }}/file/${fileId}/edit/`;
    };

    window.deleteFile = function(event, fileId, fileName) {
        event.stopPropagation();
        if (confirm(`确定要删除文件 "${fileName}" 吗？此操作不可撤销。`)) {
                            fetch(`/codes/{{ code.id }}/file/${fileId}/delete/`, {
                method: 'POST',
                headers: {
                    'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    location.reload();
                } else {
                    alert('删除失败：' + (data.error || '未知错误'));
                }
                })
            .catch(error => {
                console.error('删除失败:', error);
                        alert('删除失败，请重试');
            });
        }
    };
});

// 编辑项目信息相关函数
function openEditProjectModal() {
    const modal = new bootstrap.Modal(document.getElementById('editProjectModal'));
    const titleInput = document.getElementById('titleInput');
    const textarea = document.getElementById('descriptionTextarea');
    
    // 设置当前标题和描述内容
    const currentTitle = document.getElementById('projectTitle').textContent;
    const currentDescription = document.getElementById('projectDescription').textContent;
    
    titleInput.value = currentTitle;
    textarea.value = currentDescription === '无描述' ? '' : currentDescription;
    
    modal.show();
}

function saveProjectInfo() {
    const titleInput = document.getElementById('titleInput');
    const textarea = document.getElementById('descriptionTextarea');
    const newTitle = titleInput.value.trim();
    const newDescription = textarea.value.trim();
    
    if (!newTitle) {
        alert('项目标题不能为空');
        return;
    }
    
    // 发送AJAX请求更新项目信息
    fetch(`/codes/{{ code.id }}/update-project-info/`, {
        method: 'POST',
        headers: {
            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            title: newTitle,
            description: newDescription
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 更新页面上的标题和描述显示
            const titleElement = document.getElementById('projectTitle');
            const descriptionElement = document.getElementById('projectDescription');
            
            titleElement.textContent = newTitle;
            descriptionElement.textContent = newDescription || '无描述';
            
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('editProjectModal'));
            modal.hide();
            
            // 显示成功提示
            showSuccessMessage('项目信息更新成功！');
        } else {
            alert('更新失败：' + (data.error || '未知错误'));
        }
    })
    .catch(error => {
        console.error('更新失败:', error);
        alert('更新失败，请重试');
    });
}

function showSuccessMessage(message) {
    // 创建成功提示元素
    const alertDiv = document.createElement('div');
    alertDiv.className = 'alert alert-success alert-dismissible fade show position-fixed';
    alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    alertDiv.innerHTML = `
        <i class="fas fa-check-circle"></i> ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    `;
    
    document.body.appendChild(alertDiv);
    
    // 3秒后自动移除
    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.parentNode.removeChild(alertDiv);
        }
    }, 3000);
}
</script>
{% csrf_token %}
{% endblock %}